package com.example.petproject.service.impl;

import com.example.petproject.constants.Constants;
import com.example.petproject.entity.model.UmsUser;
import com.example.petproject.entity.vo.ReturnStatusEnum;
import com.example.petproject.execption.BaseException;
import com.example.petproject.mapper.UmsUserMapper;
import com.example.petproject.service.UmsUserService;
import com.example.petproject.util.ObjectMapperUtils;
import com.example.petproject.util.PetUmsUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 包名称：com.example.petproject.service.impl
 * 类名称：UsmUserServiceImpl
 * 类描述：用户管理Service层实现类
 * 创建人：@author DrinkMore-HotWater
 * 创建时间：2024年01月06日 10:37
 **/
@Service
public class UsmUserServiceImpl implements UmsUserService {

    private static final Logger log = LoggerFactory.getLogger(UsmUserServiceImpl.class);

    @Resource
    private UmsUserMapper umsUserMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public String loginOrAdd(String phone) {
        //先根据手机号查询用户是否存在
        UmsUser umsUser = umsUserMapper.selectUserByPhone(phone);
        if (ObjectUtils.isEmpty(umsUser)) {
            //如果当前手机号对应的用户为空则，执行新增的操作
            umsUser = new UmsUser();
            umsUser.setAccount(phone);
            umsUser.setCreatedTime(LocalDateTime.now());
            umsUser.setUpdatedTime(LocalDateTime.now());
            umsUserMapper.insertSelective(umsUser);
        }
        //生成token，并将其存入Redis，将token返回个前端
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //生成Redis key
        String tokenKey = PetUmsUtils.generateTokenRedisKey(token);
        try {
            stringRedisTemplate.opsForValue().set(tokenKey, ObjectMapperUtils.objToString(umsUser),Constants.Time.TOKEN_EFFECTIVE_TIME, TimeUnit.SECONDS);
        } catch (JsonProcessingException e) {
            if (log.isErrorEnabled()) {
                log.error("用户登录出现异常，{}",e.getMessage());
            }
            throw new BaseException(ReturnStatusEnum.SYSTEM_EXCEPTION);
        }
        return token;
    }
}
